import { Menu, Row } from 'antd';
import Sider from 'antd/es/layout/Sider';
import { useResponsive } from 'antd-style';
import { createElement, useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { swapElementsInArray } from '../../../../utils';
import { CustomBadge } from '../CustomBadge/CustomBadge.tsx';

import { Connection, House, SearchImage } from './Icons';
import { usePageMainSiderStyles } from './styles.tsx';

import type { MenuProps } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import type { FC } from 'react';

interface IPageMainSiderProps {
    incomeOffers: boolean;
}

const siderItems = [
    {
        label: 'Мои NFT',
        icon: createElement(House),
        path: '/',
    },
    {
        label: 'Обмен',
        icon: createElement(Connection),
        path: '/barter',
    },
    {
        label: 'Поиск NFT',
        icon: createElement(SearchImage),
        path: '/search',
    },
];

export const PageMainSider:FC<IPageMainSiderProps> = ({ incomeOffers }) => {
    const { styles } = usePageMainSiderStyles();
    const navigate = useNavigate();
    const { tablet, sm } = useResponsive();
    const [defaultKey, setDefaultKey] = useState([window.location.pathname]);

    const items = useMemo(() => {

        setDefaultKey([window.location.pathname]);
        const items: MenuProps['items'] = siderItems.map(
            ({ label, icon, path }) => {
                const offerBadge = path === '/barter' && incomeOffers;

                return {
                    key: path,
                    icon: offerBadge ? <CustomBadge dot={true} size="default" color="red"> <Connection /></CustomBadge> : icon,
                    label,
                };
            },
        );

        if (!sm || !tablet ) {
            return swapElementsInArray(items, 0, 1);
        }

        return items;
    }, [sm, tablet, incomeOffers]);
    
    const changeTabContent = useCallback((item: MenuInfo) => {
        navigate(item.key);
    }, [navigate]);
 
    return (

        ( !sm || !tablet )
            ? (
                <Row justify="center" align="middle" className={styles.menuMobile}>
                    <Menu
                        className={styles.menu}
                        defaultSelectedKeys={defaultKey}
                        items={items}
                        onClick={changeTabContent}
                    />
                </Row>)
            : (
                <Sider width={300} className={styles.wrapper}>
                    <Menu
                        className={styles.menu}
                        defaultSelectedKeys={defaultKey}
                        items={items}
                        onClick={changeTabContent}
                    />
                </Sider>)
        
    );
};
